package com.asiainfo.kbisheet.util.yunnan

import java.text.SimpleDateFormat;

import com.asiainfo.kbisheet.util.DBU
import com.asiainfo.kbisheet.util.DBUFactory;
import com.asiainfo.kbisheet.vo.AllExportVO;
import com.asiainfo.kbisheet.vo.QueryVO;

import flex.messaging.FlexContext;

class AllExport {
	DBU dbu = (new DBUFactory()).createDBU("teradata")
	boolean allExport(AllExportVO allExportVO,QueryVO queryVO){
		try{			
			/*把查询用数据改为导出用数据*/
			queryVO.setSourceKey("teradata")
			if(allExportVO.getExportAllDataBase() != null && allExportVO.getExportAllDataBase().length() > 0){
				queryVO.setDataBaseName(allExportVO.getExportAllDataBase())
			}
			
			if(allExportVO.getExportAllTable() != null && allExportVO.getExportAllTable().length() > 0){
				queryVO.setTableName(allExportVO.getExportAllTable())
			}
			
			/*查询user_id在teradata数据库中的portal_user_id*/
			def sql = dbu.getSQLInstance();
			def req = """
select portal_user_id as portal_user_id from bass15.tb_pt_user where user_login_name = ${allExportVO.user_id} and del_flag = 0
		"""
			println(req)
			def portalUserIdResult = sql.firstRow(req)
			def portal_user_id = portalUserIdResult.portal_user_id
			
			/*設置遠程IP*/		
			allExportVO.setHost_ip(FlexContext.getHttpRequest().getRemoteAddr())
			/*设置SQL条件*/
			allExportVO.setSql_desc(dbu.getWhereString(queryVO.getWheres(),queryVO.getColumns()))
			/*设置SQL内容*/
			allExportVO.setSql_content(getSQL(queryVO))
			/*設置日期和時間*/
			Date now = new Date()		
			SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd")
			allExportVO.setStat_day(f.format(now))
			allExportVO.setDay_time(now.getHours()*10000 + now.getMinutes()*100 + now.getSeconds())
			
			req = """
insert into bass15.tb_pt_export_data(id,stat_day,user_id,mobile,rpt_id,
 rpt_title,sql_desc,sql_content,status,
 write_log_flag,host_ip,day_time)
select max(id) + 1 ,${allExportVO.stat_day},${portal_user_id},${allExportVO.mobile},${allExportVO.rpt_id},
 ${allExportVO.rpt_title},${allExportVO.sql_desc},${allExportVO.sql_content},0,
 0,${allExportVO.host_ip},${allExportVO.day_time} 
 from bass15.tb_pt_export_data
		"""
			println(req)
			sql.execute(req)
			
		}
		catch(Throwable t){
			log.error(t,t)
			throw t
		}
		finally{
			dbu.close()
		}
		true
	}
	
	
	String getSQL(QueryVO queryVO){    	
		/*拼column字符串*/
		String columnString = dbu.getColumnString(queryVO, true)     	
		
		/*拼where字符串*/
		String whereString = dbu.getWhereString(queryVO.getWheres(),queryVO.getColumns())       
		
		String orderString = dbu.getOrderString(queryVO)
		
		String req = """
select ${columnString} from ${queryVO.dataBaseName}.${queryVO.tableName} ${whereString} ${orderString}
			"""
		req
	}
}
